﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using Benefit.Models.Sys;
namespace Benefit.Service.Month
{
    /// <summary>
    /// 账户月预期值
    /// </summary>
    public class ServiceAccountMonthExpected : Benefit.Interface.Month.IAccountMonthExpected
    {
        Benefit.DB.DBManager db = null;
        public ServiceAccountMonthExpected(Benefit.DB.DBManager db)
        {
            this.db = db;
        }

        public void Delete(int month, int year)
        {
            var query = from t in db.AccountMonthExpected where t.Year == year && t.Month == month select t;
            foreach (Models.Month.AccountMonthExpected c in query)
            {
                db.AccountMonthExpected.Remove(c);
            }
            db.SaveChanges();
        }

        /// <summary>
        /// 初始化账户月预期值
        /// </summary>
        /// <param name="week"></param>
        /// <param name="month"></param>
        /// <param name="year"></param>
        public void InitAccountMonthExpected(int month, int year)
        {
            var query = db.Accounts.ToList();
            foreach (Models.Sys.Account account in query)
            {
                Models.Month.AccountMonthExpected change = new Models.Month.AccountMonthExpected();
                change.AccountId = account.Id;
                change.Month = month;
                change.Year = year;
                var existQuery = from t in db.AccountMonthExpected where t.AccountId == account.Id && t.Month == month && t.Year == year select t;
                if (existQuery.Count() > 0)
                {
                    change = existQuery.First();
                }
                var _query = from t in db.AccountDayAnalysis where t.AccountId == account.Id && t.TradeHistory.MPdate == month && t.TradeHistory.YPdate == year orderby t.Id descending select t;
                double raiserate = 0;
                if (_query.Count() > 0)
                {
                    raiserate = Math.Round(_query.Average(a => a.RaiseRate), 2);
                }
                var _query2 = from t in db.AccountDayChange where t.AccountId == account.Id && t.TradeHistory.MPdate == month && t.TradeHistory.YPdate == year orderby t.Id descending select t;
                double avgbenefit = 0;
                if (_query2.Count() > 0)
                {
                    avgbenefit = Math.Round(_query2.Average(a => a.DayCount), 2);
                }
                change.DayCount = avgbenefit * 20 * raiserate;

                if (existQuery.Count() == 0)//没有本月数据
                {
                    db.AccountMonthExpected.Add(change);
                }
            }
            db.SaveChanges();
        }

    }
}